#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @time     : 2019-06-24 10:09
# @Author   : BYF
# file      : run.py
# @version  :

import pytest
import subprocess
from datetime import datetime
from lefull.common import log
from lefull.common.mail import send_mail
from lefull.common.file_manager import FileManager
from lefull.conf.config import Config

class RunTest(object):
    def __init__(self):
        self.config = Config()
        self.case_run_path = self.config.case_run_path  # case 运行目录
        self.report_xml_dir = self.config.report_xml_dir  # xml 报告目录
        self.report_html_dir = self.config.report_html_dir  # html 报告目录
        self.report_xml_zip_dir = self.config.report_xml_zip_dir  # xml zip目录
        self.report_html_zip_dir = self.config.report_html_zip_dir  # html zip目录
        self.report_zip_to_path = self.config.report_zip_to_path  # zip后文件存放目录

    def run(self, case_run_path=None):
        """
        :param case_run_path: 用例路径，可以是str，可以是list，可以不传
        :return:
        """

        # 组装参数
        if case_run_path is None:
            args = ['-s', '-v', self.case_run_path, '--alluredir', self.report_xml_dir]
        elif isinstance(case_run_path, str):
            args = ['-s', '-v', case_run_path, '--alluredir', self.report_xml_dir]
        elif isinstance(case_run_path, list):
            args = ['-s', '-v', '--alluredir', self.report_xml_dir]
            if len(case_run_path) > 0:
                for case_path in case_run_path:
                    args.insert(2, case_path)
            else:
                print("用例路径错误，请检查~！")
                return False
        else:
            print("用例路径错误，请检查~！")
            return False

        # 备份老的report文件
        now = datetime.now()
        old_xml_report = self.report_xml_dir + now.strftime("%Y-%m-%d %H:%M:%S")
        old_html_report = self.report_html_dir + now.strftime("%Y-%m-%d %H:%M:%S")
        FileManager.backup_file(self.report_xml_dir, old_xml_report)
        FileManager.backup_file(self.report_html_dir, old_html_report)

        # 执行用例
        try:
            pytest.main(args)
            log.info("========开始执行用例======== \n ")
        except Exception as e:
            log.error("========执行用例失败======== \n {e}".format(e=e))

        # 生成HTML报告
        cmd = "allure generate {xml_dir} -o {html_dir} --clean".format(
            xml_dir=self.report_xml_dir,
            html_dir=self.report_html_dir
        )

        try:
            subprocess.call(cmd, shell=True)
            log.info("Html报告生成成功")
        except Exception as e:
            log.error("========Html报告生成失败======== \n {e}".format(e=e))

        # 发送邮件
        if self.config.smtp_send_email == "True":
            try:
                FileManager.zip_file(self.report_html_zip_dir, self.report_zip_to_path)
                title = "接口测试报告~！"
                content = """
                    <p>同学们好~！</p>
                    <p>     这是{time}接口测试报告，请同学们查收,详情见附件~！</p>
                """.format(time=self.config.strtime)
                report_file = []
                report_file.append(self.report_zip_to_path)
                send_mail(title, content, files=report_file)
                log.info("邮件发送成功")
            except Exception as e:
                log.error("========邮件发送失败======== \n {e}".format(e=e))
                raise


def main():
    r = RunTest()
    case1 = "/Users/Moon/GIT-Data/Virtualenvs/LefullTestEnv/lefull/case/api/income_expenditure/test_query_income_expenditure_overview_by_search.py"
    case = [
        "/Users/Moon/GIT-Data/Virtualenvs/LefullTestEnv/lefull/case/api/marketing_coupon/test_app_find_can_use_coupon_list.py",
        "/Users/Moon/GIT-Data/Virtualenvs/LefullTestEnv/lefull/case/api/marketing_coupon/test_pc_find_can_use_coupon_list.py"
    ]
    r.run(case1)
    # r.run()


if __name__ == '__main__':
    main()
